#include<iostream>
#include<string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        std::cout<<"Usage: ip port";
        exit(1);
    }
    uint16_t port=std::stoi(argv[2]);
    std::string ip((char*)argv[1]);

    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    //client不需要显式bind，避免client端口冲突

    while(true)
    {
        std::string input;
        std::cout<<"Please Enter#";
        std::getline(std::cin,input);

        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        peer.sin_addr.s_addr=inet_addr(ip.c_str());

        sendto(sockfd,input.c_str(),input.size(),0,(sockaddr*)&peer,len);

        char buffer[1024];
        int n=recvfrom(sockfd,buffer,sizeof(buffer),0,(sockaddr*)&peer,&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
        }
    }

    return 0;
}